import React, { useEffect, useState } from "react";
import {
  Form,
  Input,
  InputNumber,
  DatePicker,
  Switch,
  Upload,
  Button,
  Row,
  Col,
  AutoComplete,
  TreeSelect,
} from "antd";
import { UploadOutlined } from "@ant-design/icons";
import useCloseLoadingOnMount from "../../../utils/hook/useCloseLoadingOnMount";
import goodsApi from "../../../apis/goodsApi";
import { promptResult2 } from "../../../utils/common";
import dictionarysApi from "../../../apis/dictionarysApi";
import recursion from "../../../utils/recursion";
import suppliersApi from "../../../apis/suppliersApi";
import { debounceAsync } from "../../../utils/common/debounce";
import ComponentHeader from "../../../components/Page/ComponentHeader";

const GoodAdd = () => {
  useCloseLoadingOnMount();
  const [form] = Form.useForm();
  const [goodTypes, setGoodTypes] = useState([]);
  const [loadingBtn, setLoadingBtn] = useState(false);
  const [supplierShopNameOptions, setSupplierShopNameOptions] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const res = await dictionarysApi.getDictionaryBySearchKey(
        "good_category"
      );
      recursion(res.data, "children", (tree) => {
        if (tree.children.length > 0) tree.selectable = false;
      });
      if (res.status >= 0) {
        setGoodTypes(res.data);
      }
    };
    fetchData();
  }, []);

  const onFinish = async (values) => {
    const formData = new FormData();
    for (var key in values) {
      if (
        ![
          "photo",
          "detailImages",
          "birthday",
          "isDirectly",
          "isShelve",
          "isPromote",
        ].includes(key)
      )
        formData.append(key, values[key]);
    }
    for (var key in values.photo) {
      formData.append("photo", values.photo[key].originFileObj);
    }
    for (var key in values.detailImages) {
      formData.append("detailImages", values.detailImages[key].originFileObj);
    }
    formData.append("birthday", values.birthday.format("YYYY-MM-DD HH:mm:ss"));
    formData.append("isDirectly", values.isDirectly ? 1 : 0);
    formData.append("isShelve", values.isShelve ? 1 : 0);
    formData.append("isPromote", values.isPromote ? 1 : 0);
    await promptResult2(goodsApi.addGoods(formData), setLoadingBtn, () => {
      form.resetFields();
    });
  };

  const handleAutoComplete = debounceAsync(async (text) => {
    if (text) {
      const res = await suppliersApi.getOptionByShopName(text);
      if (res.status >= 0) {
        setSupplierShopNameOptions(res.data);
      }
    }
  }, 1000);

  return (
    <div className="body-container1">
      <ComponentHeader title="商品添加" marginBottom />
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
        initialValues={{
          isDirectly: false,
          isShelve: false,
          isPromote: false,
          topLevel: 0,
          inventory: 0,
        }}
      >
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="商品名称"
              name="name"
              rules={[{ required: true, message: "请输入商品名称" }]}
            >
              <Input placeholder="请输入商品名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="商品价格"
              name="price"
              rules={[{ required: true, message: "请输入商品价格" }]}
            >
              <InputNumber
                style={{ width: "100%" }}
                min={0.01}
                step={1}
                precision={2}
                formatter={(value) => `¥ ${value}`}
                placeholder="请输入商品价格"
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="供应商"
              name="shopName"
              rules={[
                { required: true, message: "请输入供应商对应的店铺名称" },
              ]}
            >
              <AutoComplete
                options={supplierShopNameOptions}
                style={{ width: "100%" }}
                onSearch={handleAutoComplete}
                placeholder="请输入供应商对应的店铺名称"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="商品类别"
              name="goodTypeId"
              rules={[{ required: true, message: "请选择商品类别" }]}
            >
              <TreeSelect
                treeData={goodTypes}
                fieldNames={{ label: "value", value: "id" }}
                placeholder="请选择商品类别"
              ></TreeSelect>
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          label="商品描述"
          name="description"
          rules={[{ required: true, message: "请输入商品描述" }]}
        >
          <Input.TextArea rows={4} placeholder="请输入商品描述" />
        </Form.Item>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="生产日期"
              name="birthday"
              rules={[{ required: true, message: "请选择生产日期" }]}
            >
              <DatePicker
                showTime
                format="YYYY-MM-DD HH:mm:ss"
                style={{ width: "100%" }}
                placeholder="请选择生产日期"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="保质期（天）"
              name="expiryday"
              rules={[{ required: true, message: "请输入保质期" }]}
            >
              <InputNumber
                min={1}
                style={{ width: "100%" }}
                placeholder="请输入保质期"
              />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          label="商品规格"
          name="specs"
          rules={[{ required: true, message: "请输入商品规格" }]}
        >
          <Input.TextArea
            rows={2}
            onBlur={(e) =>
              form.setFieldValue(
                "specs",
                e.target.value.replaceAll("：", ":").replaceAll("；", ";")
              )
            }
            placeholder="示例：颜色:红色;尺寸:XL"
          />
        </Form.Item>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="是否直营"
              name="isDirectly"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="是否上架" name="isShelve">
              <Switch />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          label="库存"
          name="inventory"
          rules={[{ required: true, message: "请输入库存" }]}
        >
          <InputNumber
            min={0}
            style={{ width: "100%" }}
            placeholder="请输入库存"
          />
        </Form.Item>

        <Form.Item
          label="封面图片"
          name="photo"
          rules={[{ required: true, message: "请上传封面图片" }]}
          valuePropName="fileList" // 指定值来源为组件的 fileList 属性
          getValueFromEvent={(e) => e.fileList} // 将 onChange 的返回值转为表单字段值
        >
          <Upload
            listType="picture"
            maxCount={1}
            beforeUpload={() => false} // 阻止自动上传
          >
            <Button icon={<UploadOutlined />}>选择文件</Button>
          </Upload>
        </Form.Item>

        <Form.Item
          label="详情图片"
          name="detailImages"
          rules={[{ required: true, message: "请上传详情图片" }]}
          valuePropName="fileList" // 指定值来源为组件的 fileList 属性
          getValueFromEvent={(e) => e.fileList} // 将 onChange 的返回值转为表单字段值
        >
          <Upload listType="picture" multiple beforeUpload={() => false}>
            <Button icon={<UploadOutlined />}>选择文件</Button>
          </Upload>
        </Form.Item>

        <Form.Item
          label="置顶级别"
          name="topLevel"
          rules={[{ required: true, message: "请输入置顶级别" }]}
        >
          <InputNumber
            min={0}
            style={{ width: "100%" }}
            placeholder="请输入置顶级别"
          />
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            loading={loadingBtn}
            htmlType="submit"
            style={{ width: 120 }}
          >
            提交
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default GoodAdd;
